package com.yang.eduauth.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yang.commonutils.R;
import com.yang.eduauth.entity.Permission;
import com.yang.eduauth.entity.RolePermission;
import com.yang.eduauth.service.PermissionService;
import com.yang.eduauth.service.RolePermissionService;
import com.yang.eduauth.vo.MenuQuery;
import com.yang.eduauth.vo.PermissionVo;
import com.yang.eduauth.vo.TreeSelect;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yds
 * @since 2020-12-16
 */
@RestController
@RequestMapping("/eduauth/menu")
@Api(description = "菜单管理")
@CrossOrigin
public class PermissionController {

    @Autowired
    PermissionService permissionService;
    @Autowired
    RolePermissionService rolePermissionService;



    @ApiOperation("增加菜单接口")
    @PostMapping("/addMenu")
    public R addRole(@RequestBody Permission permission){
        System.out.println(permission.toString());
        boolean save = permissionService.save(permission);
        return save?R.ok():R.error();
    }
    @ApiOperation("根据id获取菜单信息")
    @GetMapping("/getUser/{id}")
    public R getRole(@PathVariable String id){
        Permission permission = permissionService.getById(id);
        return R.ok().data("item",permission);
    }
    @ApiOperation("修改菜单信息")
    @PostMapping("/updateUser")
    public R updateRole(@RequestBody Permission permission){
        boolean b = permissionService.updateById(permission);
        return b?R.ok():R.error();
    }

    @ApiOperation("修改菜单信息")
    @DeleteMapping("/moveMenu/{id}")
    public R moveMenu(@PathVariable String id){
        if (permissionService.hasChildByMenuId(id))
        {
            return R.error().message("存在子菜单，不允许删除");
        }
        if (permissionService.checkMenuExistRole(id))
        {
            return R.error().message("菜单已分配,不允许删除");
        }else {
            boolean b = permissionService.removeById(id);
            return b?R.ok():R.error();
        }
    }

    @ApiOperation("开启或关闭menu")
    @PostMapping("/enableOrOff/{id}/{status}")
    public R enableOrOff(@PathVariable("id") String id,@PathVariable("status") String status){
        //Mybatis plus默认的更新策略是NOT_NULL;即通过接口更新数据时数据为NULL值时将不更新进数据库
        Permission permission = new Permission();
        permission.setId(id);
        permission.setStatus(status);
        boolean b = permissionService.updateById(permission);
        return b?R.ok():R.error();
    }


//    @ApiOperation("修改菜单信息")
//    @PostMapping("/treeSelect")
//    public R updateRole(){
//        List<Permission> pList =permissionService.list(null);
//        final List<Permission> menus = pList.stream().filter(
//                l -> ("0".equals(l.getVisible())&&("0".equals(l.getStatus()))
//                ))
//                .collect(Collectors.toList());
//
//        return
//    }


    @PostMapping(value={"/pageMenuCondition"})
    @ApiOperation("菜单列表")
    public R getMenus(MenuQuery menuQuery) {

        QueryWrapper<RolePermission> rPWrapper = new QueryWrapper();
        List<PermissionVo> list = new ArrayList<>();
        if(!StringUtils.isEmpty(menuQuery.getRoleId())) {
            rPWrapper.eq("role_id", menuQuery.getRoleId());

            List<RolePermission> pList = rolePermissionService.list(rPWrapper);

            for (RolePermission item : pList) {
                String permissionId = item.getPermissionId();
                Permission permission = permissionService.getById(permissionId);
                PermissionVo permissionVo = new PermissionVo();
                Map<String,String> map=new HashMap<>();
                map.put("icon",permission.getIcon());
                map.put("title",permission.getName());
                String component="Layout";
                if(permission.getType().equals("C")){
                    component=permission.getComponent();
                }
                permissionVo.setId(permission.getId())
                        .setName(permission.getName())
                        .setHidden(permission.getStatus().equals("1")?true:false)
                        .setPid(permission.getPid())
                        .setPath(permission.getPath())
                        .setMeta(map)
                        .setComponent(component);
                list.add(permissionVo);

            }
        }else {
            List<Permission> pList = permissionService.list(new QueryWrapper<Permission>());
            for (Permission item : pList) {
                PermissionVo permissionVo = new PermissionVo();
                Map<String,String> map=new HashMap<>();
                map.put("icon",item.getIcon());
                map.put("title",item.getName());
                String component="Layout";
                if(item.getType().equals("C")){
                    component=item.getComponent();
                }
                permissionVo.setId(item.getId())
                        .setName(item.getName())
                        .setHidden(item.getStatus().equals("1")?true:false)
                        .setPid(item.getPid())
                        .setPath(item.getPath())
                        .setMeta(map)
                        .setComponent(component);
                list.add(permissionVo);

            }

        }
        final List<PermissionVo> menus = list.stream().filter(l -> !l.getHidden())
                .collect(Collectors.toList());
        List<PermissionVo> firstLevel = menus.stream().filter(p -> p.getPid().equals("0")).collect(Collectors.toList());
        firstLevel.parallelStream().forEach(m -> {
            setChild(m, menus);
        });

        return R.ok().data("menu",firstLevel);

    }

    /**
     * 设置子元素
     *
     * @param m
     * @param menus
     */
    private void setChild(PermissionVo m, List<PermissionVo> menus) {
        Set<PermissionVo> child = menus.parallelStream().filter(a -> a.getPid().equals(m.getId())).collect(Collectors.toSet());
        m.setChildren(child);
        if (!CollectionUtils.isEmpty(child)) {
            child.parallelStream().forEach(c -> {
                //递归设置子元素，多级菜单支持
                setChild(c, menus);
            });
        }
    }






}

